package com.killer.gateway.filter;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class LogFilter implements GlobalFilter, Ordered {

    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH");

    @Data
    static class LogInfo{
        private String method;
        private String body;
        private String url;
        private String header;
        private String result;
        private String ip;
        private long timestamp=System.currentTimeMillis();
        private String date = simpleDateFormat.format(new Date());
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //创建日志信息对象
        LogInfo logInfo=new LogInfo();
        //获取请求对象
        ServerHttpRequest serverHttpRequest=exchange.getRequest();
        //获取请求方法
        String method=serverHttpRequest.getMethodValue().toUpperCase();
        //设置请求方法
        logInfo.setMethod(method);
        logInfo.setHeader(serverHttpRequest.getHeaders().toString());
        logInfo.setUrl(serverHttpRequest.getURI().toString());
        if (StringUtils.isNotBlank(serverHttpRequest.getHeaders().getFirst("X-Real-IP"))) {
            logInfo.setIp(serverHttpRequest.getHeaders().getFirst("X-Real-IP"));
        }else{
            logInfo.setIp("IP获取异常!");
        }
        if (!StringUtils.equalsIgnoreCase("GET", method)&&!StringUtils.equalsIgnoreCase("DELETE", method)) {
            //获取请求体,直接从缓冲读取requestBody，不要再从请求中读取请求体
            String body = exchange.getAttributeOrDefault("cachedRequestBody", "");
            logInfo.setBody(body);
        }
        ServerHttpResponse serverHttpResponse=exchange.getResponse();
        DataBufferFactory bufferFactory=serverHttpResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(serverHttpResponse){
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody=(Flux<? extends DataBuffer>)body;
                    return super.writeWith(fluxBody.map(dataBuffer->{
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        DataBufferUtils.release(dataBuffer);
                        String resp = new String(content, StandardCharsets.UTF_8);
                        logInfo.setResult(resp);
                        log.info("请求信息:" + JSON.toJSONString(logInfo));
                        byte[] uppedContent=new String(content,StandardCharsets.UTF_8).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    @Override
    public int getOrder() {
        return -20;
    }
}
